import type { ActionType } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { Form, Select, message, Modal, Spin, Button } from 'antd';
import { useEffect, useRef, useState } from 'react';
import { useAccess } from 'umi';
import { handledynamicquerydata, handledynamicqueryColumns } from '@/utils'
import { request } from 'umi';
import MyEcharts from '@/components/myEcharts'
import EditCom from './edit';
import './index.less'
import { PlusOutlined } from '@ant-design/icons';
export const waitTimePromise = async (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export const waitTime = async (time: number = 100) => {
  await waitTimePromise(time);
};

export default (props: any) => {
  const requestsUrls = {
    optionUrl: '/data/dynamic/query',
    list: "/data/dynamic/query",
  };
  const [loading, setloading] = useState(true);
  const [wherecolumns, setwherecolumns]: any = useState([]);
  const [columns, setcolumns]: any = useState([]);
  const [datasource, setdatasource]: any = useState([]);
  const [paging, setpaging] = useState({});
  const [orderBy, setorderBy] = useState('');
  const [where, setwhere]: any = useState([]);
  const getOptions = async () => {
    const response: any = await request(requestsUrls.optionUrl, {
      method: 'POST',
      headers: {
        'Accept': '*/*',
        'Content-Type': 'application/json',
      },
      data: {
        "apiID": "DMT_MNG_01",
        "apiParam": {
          "api_id": "SR_GAS_001"
        }
      }
    });
    const dynamicquerydata = handledynamicquerydata(response);
    console.log(dynamicquerydata);
    setorderBy(dynamicquerydata?.orderBy);
    setpaging(dynamicquerydata?.paging);
    setwherecolumns(dynamicquerydata?.where);
    setwhere(dynamicquerydata?.where)
    setloading(false);
  }
  //获取配置文件
  useEffect(() => {
    getOptions();
  }, [])
  const getChartsOptions = (type: any) => {
    let key = '';
    switch (type) {
      case 0:
        key = '表走数';
        break;
      case 1:
        key = '日均用气量';
        break;
      default:
        break;
    }
    let xAxisArr = [];
    let yAxisArr = [];
    datasource.map((e: any, i: number) => {
      xAxisArr.push(e['账期']);
      yAxisArr.push(e[key]);
    })
    const option = {
      grid: {
        left: '8%',
        right: '8%',
        top: '12%',
        bottom: '8%'
      },
      title: {
        text: key
      },
      xAxis: {
        type: 'category',
        data: xAxisArr
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          data: yAxisArr,
          type: 'line'
        }
      ]
    };
    return option;
  }
  const actionRef = useRef<ActionType>();
  const editRef = useRef();
  const access = useAccess();
  const [form] = Form.useForm(); //搜索表单
  // const pageAuth = access[props.route.key] || {edit:true,delete:true,add:true};
  return (
    <>

      {
        loading ? <Spin>配置加载中</Spin> : <ProTable
          actionRef={actionRef}
          pagination={false}
          title={() => {
            return <>
              {
                datasource.length > 0 && <div className='chartsContainer'>

                  <div id="myChart" style={{ height: '300px' }}>
                    <MyEcharts style={{ height: '100%' }} option={getChartsOptions(0)} />
                  </div>
                  <div id="myChart1" style={{ height: '300px' }}>
                    <MyEcharts style={{ height: '100%' }} option={getChartsOptions(1)} />
                  </div>
                </div>
              }
            </>
          }}
          scroll={{ x: 1500, y: window.innerHeight - 650 }}
          columns={wherecolumns.concat(columns)}
          // search={false}
          params={form.getFieldsValue()}
          // params 是需要自带的参数
          // 这个参数优先级更高，会覆盖查询表单的参数
          request={async (
            // 第一个参数 params 查询表单和 params 参数的结合
            // 第一个参数中一定会有 pageSize 和  current ，这两个参数是 antd 的规范
            params: T & {
              pageSize: number;
              //current: number;
            },
            sort,
            filter,
          ) => {
            // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
            // 如果需要转化参数可以在这里进行修改
            const paramsdata: any = {
              "apiID": "SR_GAS_001",
              "apiParam": {
                "paging": { "pageSize": params.pageSize, "pageNum": params.current },
                "where": []
              }
            };
            if (!params['p.address1']) {
              return;
            }
            where.map((e: any, i: Number) => {
              console.log(e);
              if (params[e.key]) {
                paramsdata?.apiParam.where.push({
                  "feild": e.key,
                  "connector": e.connector,
                  "value": params[e.key]
                })
              }
            })
            //where
            const response: any = await request(requestsUrls.list, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
              data: paramsdata,
            });
            const rescolumns = response?.data?.columns || [];

            const columnsn = handledynamicqueryColumns(rescolumns);
            setcolumns(columnsn);
            setdatasource(response?.data?.data || [])
            return {
              data: response?.data?.data || [],
              // success 请返回 true，
              // 不然 table 会停止解析数据，即使有数据
              success: true,
              // 不传会使用 data 的长度，如果是分页一定要传
              total: response?.data?.count,
              //message.success(res?.meta?.msg);
            };
          }}

          toolBarRender={() => [
            <Button
              key="button"
              icon={<PlusOutlined />}
              onClick={() => {
                editRef.current?.init();
              }}
              type="primary"
            >
              新建
            </Button>
          ]}
        />
      }

      <div></div>

      <EditCom
        ref={editRef}
        callback={() => {
          actionRef.current?.reload();
        }}
      />
    </>
  );
};
